
package common.core.util;

import com.google.common.collect.Maps;

import java.util.*;

public class ListUtils {

    /**
     * @param pageSize  当前页面大小
     * @param pageNum  当前页码
     * @param list  需要分页的集合
     * @return
     */
    public static  Map  MapPager(int pageSize, int pageNum, List list){
        //使用list 中的sublist方法分页
        List dataList = new ArrayList<>();
        // 每页显示多少条记录
        Map met = Maps.newHashMap();
        int currentPage; //当前第几页数据
        int totalRecord = list.size(); // 一共多少条记录
        int totalPage = totalRecord % pageSize; // 一共多少页
        if (totalPage > 0) {
            totalPage = totalRecord / pageSize + 1;
        } else {
            totalPage = totalRecord / pageSize;
        }
        // 当前第几页数据
        currentPage = totalPage < pageNum ? totalPage : pageNum;

        // 起始索引
        int fromIndex = pageSize * (currentPage - 1);

        // 结束索引
        int toIndex = pageSize * currentPage > totalRecord ? totalRecord : pageSize * currentPage;
        try{
            if(list!=null && list.size()>0){
                dataList = new ArrayList<>(list.subList(fromIndex, toIndex));
            }
            met.put("records",dataList);
            met.put("total",totalRecord);
            met.put("current",currentPage);
        }catch(IndexOutOfBoundsException e){
            e.printStackTrace();
        }
        return met;
    }

    public static  List sort(List list){
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                String str1=(String) o1;
                String str2=(String) o2;
                if (str1.compareToIgnoreCase(str2)<0){
                    return -1;
                }
                return 1;
            }
        });
        return list;
    }

    public static boolean equalLists(List<String> one, List<String> two){
        if (one == null && two == null){
            return true;
        }

        if((one == null && two != null)
                || one != null && two == null
                || one.size() != two.size()){
            return false;
        }

        //to avoid messing the order of the lists we will use a copy
        //as noted in comments by A. R. S.
        one = new ArrayList<String>(one);
        two = new ArrayList<String>(two);

        Collections.sort(one);
        Collections.sort(two);
        return one.equals(two);
    }

}
